﻿using CodeNotes.BLL;
using CodeNotes.Common;
using CodeNotes.Model;
using MvcCodeNotes.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace MvcCodeNotes.Controllers
{
    public class MpAdminController : Controller
    {
        //
        // GET: /MpAdmin/

        public ActionResult Index()
        {
            return View();
        }   

        public ActionResult MpList()
        {
            List<MP_Setting> listTemp = new MP_SettingLogic().GetModelList("1=1 order by Id desc");
            return View(listTemp);
        }

        // GET: /MpAdmin/Edit/5

        public ActionResult MpEdit(int? id)
        {
            MP_Setting model = new MP_Setting();
            if (id > 0)
            {
                model = new MP_SettingLogic().GetModel(Convert.ToInt32(id));
            }
            return View(model);
        }

        //
        // POST: /MpAdmin/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MpEdit(int id, MP_Setting model)
        {
            try
            {
                HttpPostedFileBase thumbnail = Request.Files["thumbnail"];
                if (thumbnail != null && thumbnail.FileName != "")
                {
                    string directoryPath = Server.MapPath("~/images/mp/");
                    if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    string fileName = thumbnail.FileName;
                    string fileExt = Path.GetExtension(fileName).ToLower();
                    string logoSrc = DateTime.Now.ToString("yyyMMddHHmmss") + fileExt;
                    string savepath = directoryPath + logoSrc;
                    thumbnail.SaveAs(savepath);
                    model.Logo = logoSrc;
                }
                if (model.Id > 0)
                {
                    new MP_SettingLogic().Update(model);
                }
                else
                {
                    new MP_SettingLogic().Add(model);
                }

                return RedirectToAction("MpList");
            }
            catch
            {
                return View();
            }
        }


        [HttpPost]
        public ActionResult MpClose(int id)
        {
            try
            {
                if (id > 0)
                {
                    MP_Setting model = new MP_SettingLogic().GetModel(Convert.ToInt32(id));
                    model.RefreshEnable = !model.RefreshEnable;
                    new MP_SettingLogic().Update(model);
                }
                return RedirectToAction("MpList");
            }
            catch
            {
                return View();
            }
        }

        #region 定时更新

        //定时更新微信参数
        public ActionResult AutoUpdateSetting()
        {
            //遍历API列表，查看是否过期，过期则更新
            List<MP_Setting> settings = new MP_SettingLogic().GetModelList("RefreshEnable=1 order by Id desc");
            foreach (MP_Setting item in settings)
            {
                Int32 seconds = Convert.ToInt32(item.RefreshInterval);
                DateTime dtUpdate = Convert.ToDateTime(item.LastRefreshTime);
                if (dtUpdate.AddSeconds(seconds) < DateTime.Now)
                {
                    //到更新时间了，更新接口
                    string access_token = AutoGetAccessToken(item);
                    string JsapiTicket = "";
                    string JsapiTicketWxCard = "";
                    if(!string.IsNullOrEmpty(access_token))
                    {
                        JsapiTicket = AutoGetJsapiTicket(access_token);
                        JsapiTicketWxCard = AutoGetJsapiTicketWxCard(access_token);

                        item.AccessToken = access_token;
                        item.JsapiTicket = JsapiTicket;
                        item.JsapiTicketWxCard = JsapiTicketWxCard;
                        item.LastRefreshTime = DateTime.Now;
                        new MP_SettingLogic().Update(item);
                    }                    
                }
            }

            return View();
        }

        public string AutoGetAccessToken(MP_Setting setting)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + setting.AppId + "&secret=" + setting.AppSecrect;
            string retString = HttpWebResponseUtility.CreateGetHttpResponse(url);
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            ResponseJSON rj = Serializer.Deserialize<ResponseJSON>(retString);
            return rj.access_token;
        }

        //获取JsapiTicket,用于js分享
        public string AutoGetJsapiTicket(string access_token)
        {            
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            string Jsapi_str = HttpWebResponseUtility.CreateGetHttpResponse("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
            ResponseJSON obj = Serializer.Deserialize<ResponseJSON>(Jsapi_str);
            return obj.ticket;
        }

        //获取JsapiTicket,用于js获取卡券
        public string AutoGetJsapiTicketWxCard(string access_token)
        {            
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            string Jsapi_str = HttpWebResponseUtility.CreateGetHttpResponse("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=wx_card");
            ResponseJSON obj = Serializer.Deserialize<ResponseJSON>(Jsapi_str);
            return obj.ticket;
        }

        #endregion
    }
}
